package middleware

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"strings"
	"web-server/pkg/jwt"
	"web-server/pkg/log"
)

type LoginJWTMiddlewareBuilder struct {
	ignorePaths  []string
	includePaths []string
}

func NewLoginJWTMiddlewareBuilder() *LoginJWTMiddlewareBuilder {
	return &LoginJWTMiddlewareBuilder{}
}

func (l *LoginJWTMiddlewareBuilder) IgnorePaths(paths []string) *LoginJWTMiddlewareBuilder {
	l.ignorePaths = paths
	return l
}
func (l *LoginJWTMiddlewareBuilder) IncludePaths(paths []string) *LoginJWTMiddlewareBuilder {
	l.includePaths = paths
	return l
}

func (l *LoginJWTMiddlewareBuilder) Build() gin.HandlerFunc {
	return func(c *gin.Context) {

		reqPath := c.Request.URL.Path

		if len(l.ignorePaths) > 0 {
			for _, path := range l.ignorePaths {
				if strings.HasPrefix(reqPath, path) {
					c.Next()
					return
				}
			}
		} else {
			// 只有includePaths里的路径才需要验证
			for _, path := range l.includePaths {
				fmt.Println(path, l.includePaths)
				if !strings.HasPrefix(reqPath, path) {
					c.Next()
					return
				}
			}
		}

		authToken := c.Request.Header.Get("Authorization")
		logger := log.Default()
		uid := jwt.ValidateTokenAndGetUid(authToken)
		if uid == 0 {
			c.JSON(401, gin.H{
				"message": "token parse errno",
			})
			logger.Z.Error("token parse errno")
			c.Abort()
			return
		}
		c.Set("uid", uid)
		fmt.Println(uid)
	}
}
